import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @program: LeetCode
 * @description: LeetCode : 139. 单词拆分
 * @author: WXY
 * @create: 2023-01-12 17:40
 * @Version 1.0
 **/
public class Num139_wordBreak {
    //由于是是wordDict中的单词组成S，所以单词的组合是有顺序的，，
    //所以这个是一个排列问题
    //外背包，内物品

    //    如果求组合数就是外层for循环遍历物品，内层for遍历背包。
//    如果求排列数就是外层for遍历背包，内层for循环遍历物品。
    public static boolean wordBreak1(String s, List<String> wordDict) {
        HashSet<String> set = new HashSet<>(wordDict);
        int len = s.length();
        boolean[] dp = new boolean[len + 1];
        dp[0] = true;
        for (int i = 1; i <= len; i++) {
            for (int j = 0; j < i && !dp[i]; j++) {
                if (set.contains(s.substring(j, i)) && dp[j]) {
                    dp[i] = true;
                }
            }
        }
        return dp[len];
    }

    public static boolean wordBreak(String s, List<String> wordDict) {
        int len = s.length();
        boolean[] dp = new boolean[len + 1];
        dp[0] = true;
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < i && !dp[i]; j++) {
                if (wordDict.contains(s.substring(j, i)) && dp[j]) {
                    dp[i] = true;
                }
            }
        }
        return dp[len];
    }
    
    
    public static void main(String[] args) {
        String str = "catsandog";
        List<String> list = new ArrayList<>();
        list.add("cats");
        list.add("dog");
        list.add("sand");
        list.add("and");
        list.add("cat");
        boolean b = wordBreak1(str, list);
        System.out.println(b);
        System.out.println(wordBreak(str,list));
    }
}
